/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import $ from 'jquery';
import isEqual from 'react-fast-compare';
import { Icon as IconBp, Menu, MenuItem } from '@blueprintjs/core';
import { Icon } from 'antd';

// Services
import { QueryService } from '../../../../services';

// Actions
import { actionCreators } from '../../../../actions';

// UI
import { BlockUi } from '../../../UI';

// Utils
import { Saiku } from '../../../../utils';

// Styles
import './WTChartMenu.css';

// Constants
const ICON_FONT_SIZE = '25px';
const ICON_COLOR = 'gray';
const ICON_THEME = 'filled';

class WTChartMenu extends Component {
  shouldComponentUpdate(nextProps, nextState) {
    return !isEqual(this.props.chartItems, nextProps.chartItems);
  }

  handleExportChart(fileType) {
    const { requestStart, requestSuccess, requestFailure } = this.props;

    requestStart(
      <BlockUi message={`Exporting ${fileType.toUpperCase()} file...`} />
    );

    QueryService.exportChart(fileType)
      .then(res => requestSuccess())
      .catch(error => requestFailure());
  }

  handleChartType = event => {
    const { setChartType } = this.props;
    const type = event.currentTarget.getAttribute('type');

    setChartType('chart', type);
  };

  renderChartItems() {
    const { hasResultset, chartItems, type } = this.props;
    const chartItemsElem = chartItems.map(chart => (
      <MenuItem
        key={Saiku.uid(chart.id)}
        type={chart.id}
        icon={
          <img
            src={type === chart.id ? chart.pathActive : chart.pathDefault}
            alt={chart.title}
          />
        }
        text={chart.title}
        active={type === chart.id}
        disabled={chart.disabled}
        onClick={this.handleChartType}
      />
    ));

    chartItemsElem.unshift(
      <MenuItem
        key={Saiku.uid('export')}
        icon={
          <IconBp
            icon="export"
            iconSize={18}
            style={{ margin: '0 15px 0 3px' }}
          />
        }
        text="Export"
        disabled={!hasResultset || !type}
      >
        <MenuItem
          icon={
            <Icon
              type="file-image"
              style={{ fontSize: ICON_FONT_SIZE, color: ICON_COLOR }}
              theme={ICON_THEME}
            />
          }
          text="To PNG"
          onClick={this.handleExportChart.bind(this, 'png')}
        />
        <MenuItem
          icon={
            <Icon
              type="file-pdf"
              style={{ fontSize: ICON_FONT_SIZE, color: ICON_COLOR }}
              theme={ICON_THEME}
            />
          }
          text="To PDF"
          onClick={this.handleExportChart.bind(this, 'pdf')}
        />
      </MenuItem>
    );

    return chartItemsElem;
  }

  render() {
    const menuHeight = $('body').height() / 2 + $('body').height() / 6;

    return (
      <Menu
        className="sku-chart-menu"
        style={{ overflowY: 'auto', maxHeight: menuHeight }}
      >
        {this.renderChartItems()}
      </Menu>
    );
  }
}

WTChartMenu.propTypes = {
  hasResultset: PropTypes.bool.isRequired,
  chartItems: PropTypes.array.isRequired,
  type: PropTypes.string,
  setChartType: PropTypes.func.isRequired,
  requestStart: PropTypes.func.isRequired,
  requestSuccess: PropTypes.func.isRequired,
  requestFailure: PropTypes.func.isRequired
};

WTChartMenu.defaultProps = {
  type: 'bar'
};

const mapDispatchToProps = dispatch => ({
  requestStart: message => dispatch(actionCreators.requestStart(message)),
  requestSuccess: () => dispatch(actionCreators.requestSuccess()),
  requestFailure: () => dispatch(actionCreators.requestFailure())
});

export default connect(
  null,
  mapDispatchToProps
)(WTChartMenu);
